import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hj_crm/entity/order_info.dart';
import 'package:hj_crm/entity/pagination.dart';
import 'package:hj_crm/form/order_form.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/utils/perms_check.dart';
import 'package:hj_crm/widget/load_more_widget.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

typedef OrdersChanged = void Function(List<OrderInfo> ordersData);

/// 用户列表
class OrderListWidget extends StatefulWidget {
  final String uId;
  const OrderListWidget({super.key, required this.uId});

  @override
  State<OrderListWidget> createState() => _OrderListState();
}

class _OrderListState extends State<OrderListWidget> {
  List<OrderInfo> orders = <OrderInfo>[];
  OrderDataSource? dataSource;

  RequestRepository repository = Get.find<RequestRepository>();

  /// 新增订单
  final bool _canAdd = PermsCheck.customerOrderAdd();
  final bool _canDelete = PermsCheck.customerOrderDelete();
  final bool _canUpdate = false;

  bool canSwiper = false;

  int maxOffset = 100;

  @override
  void initState() {
    super.initState();

    canSwiper = _canDelete;
    maxOffset = _canDelete ? 100 : 0;
    refreshOrderList();
  }

  refreshOrderList() {
    repository.findOrderList(
      uId: widget.uId,
      success: (data) {
        setState(() {
          orders = data.data;
          dataSource = OrderDataSource(
            ordersData: orders,
            pagination: data.pagination,
            uId: widget.uId,
            dataChanged: (ordersData) => orders = ordersData,
          );
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('购买记录'),
      ),
      body: dataSource == null
          ? Center(
              child:
                  CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.deepPurple)))
          : SafeArea(
              child: SfDataGrid(
                source: dataSource!,
                columnWidthMode: ColumnWidthMode.fill,
                onCellTap: (details) {
                  if (_canUpdate == false) {
                    return;
                  }
                  if (details.rowColumnIndex.rowIndex == 0) {
                    return;
                  }
                  Navigator.of(context)
                      .push(MaterialPageRoute(
                    builder: (context) => OrderFormWidget(
                      uId: orders[details.rowColumnIndex.rowIndex - 1].userInfoId.toString(),
                    ),
                  ))
                      .then((v) {
                    if (v == true) refreshOrderList();
                  });
                },
                allowSwiping: canSwiper,
                swipeMaxOffset: maxOffset.toDouble(),
                allowPullToRefresh: true,
                loadMoreViewBuilder: loadMoreBuilder,
                onSwipeStart: (swipeStartDetails) {
                  if (canSwiper == false) {
                    return false;
                  }
                  if (swipeStartDetails.swipeDirection == DataGridRowSwipeDirection.startToEnd) {
                    swipeStartDetails.setSwipeMaxOffset(100);
                    return true;
                  } else {
                    return false;
                  }
                },
                startSwipeActionsBuilder: (context, dataGridRow, rowIndex) {
                  return _canDelete
                      ? InkWell(
                          child: Container(
                            height: double.infinity,
                            width: 100,
                            alignment: Alignment.center,
                            color: Colors.red,
                            child: Text('删除'),
                          ),
                          onTap: () {
                            repository.deleteOrder(
                              ids: [orders[rowIndex].id!],
                              success: (data) => dataSource?.deleteRow(rowIndex),
                            );
                          },
                        )
                      : null;
                },
                columns: <GridColumn>[
                  GridColumn(
                      columnName: 'name',
                      label: Container(
                          padding: EdgeInsets.all(16.0),
                          alignment: Alignment.center,
                          child: Text(
                            '商品名称',
                          ))),
                  GridColumn(
                    columnName: 'count',
                    label: Container(
                      padding: EdgeInsets.all(8.0),
                      alignment: Alignment.center,
                      child: Text('购买数量'),
                    ),
                  ),
                  GridColumn(
                      columnName: 'amount',
                      label: Container(
                          padding: EdgeInsets.all(8.0),
                          alignment: Alignment.center,
                          child: Text(
                            '金额',
                          ))),
                  GridColumn(
                    columnName: 'time',
                    label: Container(
                      padding: EdgeInsets.all(8.0),
                      alignment: Alignment.center,
                      child: Text('购买时间'),
                    ),
                  ),
                ],
              ),
            ),

      /// 新增用户
      floatingActionButton: _canAdd
          ? FloatingActionButton(
              onPressed: () {
                Navigator.of(context)
                    .push(MaterialPageRoute(builder: (context) => OrderFormWidget(uId: widget.uId)))
                    .then((v) {
                  if (v == true) refreshOrderList();
                });
              },
              tooltip: '添加订单',
              child: const Icon(Icons.add),
            )
          : null, // This
    );
  }
}

class OrderDataSource extends DataGridSource {
  OrderDataSource({
    required List<OrderInfo> ordersData,
    Pagination? pagination,
    required OrdersChanged dataChanged,
    String uId = '',
  }) {
    _uId = uId;
    _infos = ordersData;
    _pagination = pagination;
    _dataChanged = dataChanged;
    _ordersData = ordersData
        .map<DataGridRow>((e) => DataGridRow(cells: [
              DataGridCell<String>(columnName: 'name', value: e.productName),
              DataGridCell<int>(columnName: 'count', value: e.productNum),
              DataGridCell<num>(columnName: 'amount', value: e.amount),
              DataGridCell<String>(columnName: 'time', value: e.buyTime),
            ]))
        .toList();
  }

  String _uId = '';

  OrdersChanged? _dataChanged;

  List<DataGridRow> _ordersData = [];

  int _page = 1;

  Pagination? _pagination;

  List<OrderInfo> _infos = [];

  @override
  List<DataGridRow> get rows => _ordersData;

  RequestRepository repository = Get.find<RequestRepository>();

  bool get canLoadMore {
    if (_pagination == null) {
      return true;
    }
    if (_pagination!.size! * _page > _pagination!.total!) {
      return false;
    }
    return true;
  }

  void deleteRow(int index) {
    _infos.removeAt(index);
    _ordersData.removeAt(index);
    _pagination = Pagination(
      size: _pagination!.size,
      total: (_pagination!.total! - 1),
      page: _page,
    );
    notifyListeners();
  }

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((e) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(8.0),
        child: Text(e.value.toString()),
      );
    }).toList());
  }

  @override
  Future<void> handleRefresh() {
    _page = 1;
    repository.findOrderList(
      uId: _uId,
      success: (data) {
        _infos = data.data;
        _pagination = data.pagination;
        _dataChanged?.call(_infos);
        _ordersData = _infos
            .map<DataGridRow>((e) => DataGridRow(cells: [
                  DataGridCell<String>(columnName: 'name', value: e.productName),
                  DataGridCell<int>(columnName: 'count', value: e.productNum),
                  DataGridCell<num>(columnName: 'amount', value: e.amount),
                  DataGridCell<String>(columnName: 'time', value: e.buyTime),
                ]))
            .toList();
        notifyListeners();
      },
    );

    return super.handleRefresh();
  }

  @override
  Future<void> handleLoadMoreRows() async {
    if (!canLoadMore) {
      return super.handleLoadMoreRows();
    }
    _page += 1;
    repository.findOrderList(
      uId: _uId,
      page: _page,
      success: (data) {
        _infos.addAll(data.data);
        _pagination = data.pagination;
        _dataChanged?.call(_infos);
        _ordersData.addAll(data.data
            .map<DataGridRow>((e) => DataGridRow(cells: [
                  DataGridCell<String>(columnName: 'name', value: e.productName),
                  DataGridCell<int>(columnName: 'count', value: e.productNum),
                  DataGridCell<num>(columnName: 'amount', value: e.amount),
                  DataGridCell<String>(columnName: 'time', value: e.buyTime),
                ]))
            .toList());
        notifyListeners();
      },
    );
    return super.handleLoadMoreRows();
  }
}
